# -*- coding: utf-8 -*-
from django.db import models
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes import generic
from django.conf import settings
from pygameweb import markup
from django.contrib.auth.models import User

_sys_ = settings.SYS_USERNAME

class UserCommentManager(models.Manager):
    """
    Comment manager that excludes autocomments
    """
    def get_query_set(self):
        return super(UserCommentManager,
                     self).get_query_set().exclude(user__username=_sys_)


class Comment(models.Model):
    """
    generic comment model for news,projects etc..
    use like: Comment.objects.filter( content_object=news ) to get all comments for an object.
    Comment(content_object=news, user=request.user ..... ) to create a comment for an object
    """
    
    #content type fields to tie comment into a Model
    content_type = models.ForeignKey(ContentType)
    object_id = models.PositiveIntegerField()
    content_object = generic.GenericForeignKey('content_type', 'object_id')
    
    #comment fields
    markup = models.CharField(max_length=5, choices=markup.CHOICES)
    user = models.ForeignKey(User, null=True)
    content = models.TextField(max_length=1000)
    raw_content = models.TextField(editable=False)
    created = models.DateTimeField(auto_now_add=True)
    last_editor = models.ForeignKey(User, null=True, related_name="lasteditor")
    last_edited = models.DateTimeField(auto_now=True)
    
    user_comments = UserCommentManager()
    objects = models.Manager()
                      
    class Meta:
        verbose_name = "comment"
        verbose_name_plural = "comments"
        ordering = ["-created"]        
        
    def save(self):
        self.render_markup()
        if not self.user:
            self.user = User.objects.get(username=_sys_)
        super(Comment, self).save()
        
    def render_markup(self):
        self.raw_content = markup.render(self.content, self.markup)
        
    def get_absolute_url(self):
        return "%s#%s" % (self.content_object.get_absolute_url(),
                          self.short_id())
        
    def get_user_perms(self, user):
        "returns (can_edit, can_delete)"
        perms = [0, 0]
        if user == self.user:
            perms = [1, 1]
        else:
            # autocomment for project
            if hasattr(self.content_object, "admins"):
                if user in self.content_object.admins.all() or \
                   user in self.content_object.members.all():
                   perms = [1, 1]
        
        if not perms[0]: 
            perms[0] = user.has_perm("comments.change_comment")
        if not perms[1]: 
            perms[1] = user.has_perm("comments.delete_comment")
        return perms
    
    def is_auto_comment(self):
        return self.user.username == _sys_
    
    def short_id(self):
        """returns a base62 shorted id for html-id"""
        alphabets = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
        n = len(alphabets)
        num = self.id
        rv = ""
        while num != 0:
            rv = alphabets[num % n] + rv
            num /= n
        return "c%s" % rv

    
    def __unicode__(self):
        return "%s about %s ``%s`` at %s" % ((self.user or "information"), 
                                           self.content_type,
                                           self.content_object, 
                                           self.created.strftime("%x, %X"))
                                           